/**
 * Created by hama on 2016/11/11.
 */
//发送一个请求所有留言的message请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        //发送已经成功了
        // [{数据1},{数据2}] 字符串
        //console.log(xhr.responseText);
        var arr = JSON.parse(xhr.responseText);
        //console.log(arr);
        var result = '';
        for(var i=arr.length-1;i>-1;i--){
            var message = arr[i];
            //console.log (arr[i]);
            result += '<section>';
            result += '<p>';
            result += message.content;
            result += '<span>';
            result += formatTime(message.time);
            result += '</span>';
            result += '</p>';
            result += '<div>';
            result += formatIp(message.ip);
            result += '</div>';
            result += '</section>';
        }
        document.querySelector('article').innerHTML = result;
    }
}
xhr.open('GET','/message');
xhr.send();

function formatTime(time){
    var time = new Date(time);
    var year = time.getFullYear() ;
    var month = time.getMonth();
    var day = time.getDate();
    var  h = time.getHours();
    var min = time.getMinutes();

    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day ;
    h = h < 10 ? '0' + h : h;
    min = min < 10 ? '0' + min : min;

    return year + ' ' + month + ' ' + day + ' ' + '-' + h + ':' + min;
}
function formatIp(ip){
    if(ip.startwith('::1')){
       return '127.0.0.1';
    }
}